package com.station.Activitys.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.station.Activitys.R;
import com.station.Activitys.adapter.base.BaseRecyclerViewAdapter;
import com.station.Activitys.bean.UploadImage;
import com.station.Activitys.utils.Constant;
import com.station.Activitys.utils.FileUtils;
import com.station.Activitys.utils.LogUtils;
import com.station.Activitys.utils.ToastUtils;
import com.station.Activitys.view.ProcessJustImageView;
import com.zhy.autolayout.utils.AutoUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.github.lizhangqu.coreprogress.ProgressHelper;
import io.github.lizhangqu.coreprogress.ProgressUIListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 项目名称：基站管理平台 手机app
 * 类描述：公用 图片上传 适配器
 * 创建人：张飞祥
 * 创建时间：2018/8/30 15:00
 * 修改人：张飞祥
 * 修改时间：2018/8/30 15:00
 * 修改备注：
 */
public abstract class DemoUploadAdapter extends BaseRecyclerViewAdapter {

    //全局 上下文
    private Context mContext;

    //本地图片地址 Uri
    private List<String> mLocalImgList = null;
    //上传图片 的 Flag （true：当前位置可以继续上传，false：当前位置不可以上传了）
    private List<Boolean> mHttpImgFlag = null;
    //上传的图片的 Url
    private List<String> mHttpImgList = new ArrayList<>();

    /**
     * 全局构造方法
     *
     * @param mContext
     * @param mLocalImgList
     */
    public DemoUploadAdapter(Context mContext, List<String> mLocalImgList,List<String> mHttpList,List<Boolean> mFlagList) {
        super(mContext, mLocalImgList);
        this.mContext = mContext;
        this.mLocalImgList = mLocalImgList;
        this.mHttpImgList = mHttpList;
        this.mHttpImgFlag = mFlagList;
    }

    /**
     * 数据大小
     *
     * @return
     */
    @Override
    public int getItemCount() {
        //return mList.size() + 1;//因为最后多了一个添加图片的ImageView
        int count = mLocalImgList == null ? 1 : mLocalImgList.size() + 1;
        if (count > Constant.MAX_SELECT_PIC_NUM) {
            return mLocalImgList.size();
        } else {
            return count;
        }
    }

    @Override
    protected int getLayoutItemResId() {
        return R.layout.item_imge_upload;
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
        if (viewHolder instanceof ImageUploadViewHolder) {
            //TODO 获取统计上传 viewHolder
            final ImageUploadViewHolder holder = (ImageUploadViewHolder) viewHolder;
            //TODO View 非空判断
            if (holder.itemView != null) {

                /**
                 * 准备工作
                 */
                //将数据保存在itemView的Tag中，以便点击时进行获取
                holder.itemView.setTag(holder.getAdapterPosition());
                //获取 JustImageView 控件
                final ProcessJustImageView ivUpload = holder.ivItemUpload;
                //获取 删除控件
                ImageView ivDel = holder.ivItemDel;

                //TODO 图片 url
                Uri imgUri = null;

                /**
                 * 业务逻辑 判断，是否 需要显示 添加按钮
                 */
                if (position < mLocalImgList.size()) {
                    //代表+号之前的需要正常显示图片
                    String picUrl = mLocalImgList.get(position); //图片路径

                    if (!"".equals(picUrl) && picUrl !=null){
                        //获取当前路径 Uri
                        imgUri = Uri.fromFile(new File(picUrl));
                        //显示相应的图片
                        ivUpload.setImageURI(imgUri);
                        //显示 删除按钮
                        ivDel.setVisibility(View.VISIBLE);

                        if (mHttpImgFlag.get(position)){
                            //开始上传文件
                            uploadFile(imgUri,position,ivUpload);
                        }
                    }
                } else {
                    //隐藏 删除按钮
                    ivDel.setVisibility(View.GONE);
                    ivUpload.setImageResource(R.drawable.ic_add_img);//最后一个显示加号图片
                }

                /**
                 * 删除 按钮点击事件
                 */
                ivDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        delImage(position,mHttpImgList);
                    }
                });
            }
        }
    }


    //删除某一张图片 提供给 外部方法
    public abstract void delImage(int position, List<String> httpList);

    //给外部 暴露 删除某一个图片
    public void setDeleteItemImg(int position){

        //初始化 某一个图片上传标记
        mHttpImgFlag.set(position,true);
        //清除某一条的 图片 http Url
        mHttpImgList.remove(position);

        //刷新
        notifyDataSetChanged();
    }

    /**
     * 获取当前 上传到 服务器 图片的地址
     */
    public List<String> getHttpUrls() {
        return mHttpImgList;
    }

    /**
     * 文件上传 带进度 （okHttp）
     *
     * @param uri
     */
    private void uploadFile(final Uri uri, final int position, final ProcessJustImageView imageView) {

        //获取 要上传的 文件 path
        String filePath = FileUtils.getRealFilePath(mContext, uri);
        //添加要上传的文件
        File uploadFile = new File(filePath);
        //要上传的 地址
        String url = Constant.HTTP_URL + "Common/UploadImg?folderName=Survey";
//        String url = "http://101.53.102.10:8818/RFIs/AppUploaderRFIsImg";

        //TODO 创建一个 okHttp 请求
        OkHttpClient okHttpClient = new OkHttpClient();

        //TODO 创建 一个 bodyBuilder
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
        bodyBuilder.setType(MultipartBody.FORM);

        //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是file
        //此处应该改变
        bodyBuilder.addFormDataPart("file", uploadFile.getName(), RequestBody.create
                (MediaType.parse("application/octet-stream"), uploadFile));
        //构建
        MultipartBody multipartBody = bodyBuilder.build();

        //TODO  获取 上传进度
        RequestBody requestBody = ProgressHelper.withProgress(multipartBody, new ProgressUIListener() {
            @Override
            public void onUIProgressStart(long totalBytes) {
                super.onUIProgressStart(totalBytes);
                LogUtils.i("uploadFile：--------------->开始上传");
            }

            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, final float percent, float speed) {
                imageView.setProgress((int) (100 * percent));
                LogUtils.i("uploadFile：--------------->" + (int) (100 * percent));
            }

            @Override
            public void onUIProgressFinish() {
                super.onUIProgressFinish();
                LogUtils.i("uploadFile：--------------->结束上传");
            }
        });

        //创建Request
        Request request = new Request.Builder().url(url).post(requestBody).build();

        //TODO 获取当前网络请求状态
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            //请求出错
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            //请求成功 返回结果
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                String responseData = response.body().string();
                //开始解析 转换为 实体数据
                Gson gson = new Gson();
                UploadImage image = gson.fromJson(responseData + "", UploadImage.class);
                //已经上传过的 图片不允许在上传了
                mHttpImgFlag.set(position,false);

                //TODO 网络请求业务逻辑判断
                if (image.getState().equals("1")) {
                    mHttpImgList.add(image.getSrc());
                } else {
                    ToastUtils.showShort(mContext,image.getMsg());
                }
            }
        });
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        return new ImageUploadViewHolder(view);
    }


    /**
     * ViewHolder
     */
    public class ImageUploadViewHolder extends RecyclerView.ViewHolder {

        //上传图片
        @Bind(R.id.iv_item_upload)
        ProcessJustImageView ivItemUpload;
        //删除图片
        @Bind(R.id.iv_item_del)
        ImageView ivItemDel;

        public ImageUploadViewHolder(View itemView) {
            super(itemView);
            /**
             * 初始化控件
             */
            ButterKnife.bind(this, itemView);
            //屏幕适配
            AutoUtils.autoSize(itemView);
        }
    }
}
